import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router-dom'
import { inject, observer } from 'mobx-react'

import getDisplayName from './getName'
import UserStore from '../stores/user_store'


const pushHistory = (Component) => {
  @inject((stores) => {
    const store = {
      user: stores.user,
    }
    return store
  })
  @observer
  class PushHistory extends React.Component {
    constructor(props) {
      super(props)
      this.shouldLogin = this.shouldLogin.bind(this)
    }
    shouldLogin() {
      const { history, location, user } = this.props
      if (user.isLogin) {
        return true
      }
      const pathname = `/login/${encodeURIComponent(location.pathname)}`
      history.push(pathname)
      return false
    }
    push(pathname) {
      const { history } = this.props
      history.push(pathname)
    }
    render() {
      return (
        <Component {...this.props} shouldLogin={this.shouldLogin} push={this.push} />
      )
    }
  }
  PushHistory.displayName = getDisplayName(Component)
  PushHistory.propTypes = {
    history: PropTypes.objectOf(Object),
    location: PropTypes.objectOf(Object),
    user: PropTypes.instanceOf(UserStore),
  }
  return withRouter(PushHistory)
}

export default pushHistory
